// pages/personal/index/index.js
var util = require('../../../../utils/util')   //引入配置公共请求接口
import { centerCount , getCarNumber, decryptGetPhone} from '../../../../config/config'
//获取应用实例
const app = getApp()
// pages/personal/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    footprintGuid: '', //足迹全局id
    count: {},
    userInfo: {},
    phoneNumber: '',
    isShowPartnerAll:true,
    carGoods:0,
    sessionFrom:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCarGoodsNumber()
    this.setServiceUserInfo()
  },
      // 展示合伙人二维码
      partnerCode: function(e) {
        const codeImg = e.target.dataset.url
        wx.previewImage({
          urls: [codeImg],
          current: codeImg // 当前显示图片的http链接
        })
      },
      // 关闭合伙人二维码
      closeCodePop: function() {
        this.setData({
          showPartnerCodePop: false
        })
      },
      // 拨打合伙人电话
      partnerPhone: function() {
        const that = this
        wx.makePhoneCall({
          phoneNumber: that.data.partnerInfo.partnerPhone
        })
      },
     // 展开合伙人信息
     showPartnerAll: function() {
      this.setData({
        isShowPartnerAll:!this.data.isShowPartnerAll
      })
    },
  setServiceUserInfo() {
    //设置客服会话中客户微信信息
    let wxUserInfo = {}
    let userInfo = wx.getStorageSync('loginMsg').userInfo
    console.log('登录信息哈哈',userInfo)
    wxUserInfo.nickName = userInfo.nickname
    if (userInfo.gender) {
      if ('male' === userInfo.gender) {
        wxUserInfo.gender = 1
      } else if ('female' === userInfo.gender) {
        wxUserInfo.gender = 2
      }
    } else {
      wxUserInfo.gender = 0
    }
    wxUserInfo.city = userInfo.city
    wxUserInfo.province = userInfo.province
    wxUserInfo.country = userInfo.country
    wxUserInfo.avatarUrl = userInfo.icon
    this.setData({
      sessionFrom: JSON.stringify(wxUserInfo)
    })
    console.log('客户微信信息', this.data.sessionFrom)
  },
  gotopersonalData() {
    wx.navigateTo({
      url: '../personalData/personalData?userInfo=' + JSON.stringify(this.data.userInfo)
    })
  },
  // 我的足迹
  goFootprint() {
    wx.navigateTo({
      url: '../myFootprint/myFootprint'
    })
  },
  goCollection() {
    wx.navigateTo({
      url: '../myCollection/myCollection'
    })
  },
  myOrder() {
    wx.navigateTo({
      url: '../myOrder/myOrder'
    })
  },
   // 获取个人中心统计
   getcenterCount() {
    app.reqFun.requestJson('GET',centerCount,'',(res)=>{
      if(res.data.success === 1) {
        let phone = res.data.data.userInfo.phone
        let phoneNumber
        if (phone) {
          phoneNumber = phone.substring(0, 3) + '****' + phone.substring(7);
        }
        this.setData({
          count: res.data.data.count,
          userInfo: res.data.data.userInfo,
          phoneNumber: phoneNumber
        })
      }
    })
  },
  gomyOrder(e) {
    console.log('e', e)
    let status = e.currentTarget.dataset.data
    wx.navigateTo({
      url: '../../personal/myOrder/myOrder?status=' + status,
    })
  },
  returnRefund() {
    wx.navigateTo({
      url: '../../personal/myOrder/returnRefund/returnRefund',
    })
  },
  myCard(){
    wx.navigateTo({
      url: '../../coupon/myCoupon/myCoupon',
    })
  },

  getCarGoodsNumber() { //查询购物车商品数-
    var that = this;
    app.reqFun.requestJson('POST',getCarNumber, '', (res) => {
      if (res.data.success == 1) {
        that.setData({
          carGoods: res.data.data
        })
      }
    }, true)
  },
  commonProblem() {
    wx.navigateTo({
      url: '/packagBuy/pages/commonProblem/index/index'
    })
  },
  myCutPrice() {
    wx.navigateTo({
      url: '/packageLive/pages/cutPrice/list/list'
    })
  },
  gopartner(e){    //进入合伙人
    if(!wx.getStorageSync('loginMsg').partner){
      wx.navigateTo({
        url: '../../partnerLogin/partnerLogin'
      })
    }else{
      wx.navigateTo({
        url: '../../partner/partner',
      })
    }
  },
  appointment() {
    wx.showToast({
      title: '功能开发中，敬请期待哟',
      icon: 'none',
      duration: 3000
    })
  },
  // 美搭小程序跳转
  goVipMiniProgram() {
    //校验用户信息和电话是否授权
    if (!this.data.userInfo.nickname) {
      wx.showToast({
        title: '请先点击登录',
        icon: "error",
        duration: 2000
      })
      return false;
    }
    if (!this.data.userInfo.phone) {
      wx.showToast({
        title: '请先绑定手机号',
        icon: "error",
        duration: 2000
      })
      return false;
    }
    wx.navigateToMiniProgram({
      appId: 'wx86c27e0af72ae916', //会员小程序appid
      path: '', //跳转关联小程序app.json配置里面的地址
      extraData: {
        foo: 'bar'
      },
    //**重点**要打开的小程序版本，有效值 develop（开发版），trial（体验版），release（正式版）
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      footprintGuid: util.guid()
    })
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    //保存访问足迹
    app.saveAccessFootprint(this.data.footprintGuid, 'personalCenter', null)
    this.getcenterCount()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }

  getLogin(){   //登录调用 - 弹出登录窗
    var that=this;
    wx.getSetting({
      success: (res) => {
      var statu = res.authSetting;
      if (!statu['scope.userLocation']) { //没授权
        that.setData({
          'showSetting':true,
          'getSetting':true
        })
      }else{
        if(!wx.getStorageSync('loginMsg').loginState){
          if (wx.getUserProfile) {
            app.getUserProfile(function(){
              that.setData({
                getPhoneNumberData:{
                  isShowGetPhoneNumber:true
                }
              })
            })
          } else {
            if(!wx.getStorageSync('loginMsg').bindingPhone){
              that.setData({
                getPhoneNumberData:{
                  isShowGetPhoneNumber:true
                }
              })
            } else {
              that.getcenterCount()  //低版本微信绑过电话视为已登录
            }
          }
          // this.setData({
          //   isShowGetUserInfo:true
          // })
             //需要登录
        }else{
          that.getcenterCount()
            //已登录
        }
      }
    }
  })
  },
  /**绑定手机号 ---start*/
  closeGetphone(){
    this.setData({
      getPhoneNumberData:{
        isShowGetPhoneNumber:false
      }
    })
    this.getcenterCount()
  },
  getPhoneNumber(e){
    let loginMsg = wx.getStorageSync('loginMsg')
    if (e.detail.iv && e.detail.encryptedData) {
      let option = {}
      option.encryptedData = e.detail.encryptedData
      option.iv = e.detail.iv
      option.openid = loginMsg.openid
      option.session_key = loginMsg.session_key
      app.reqFun.requestJson('POST',decryptGetPhone,option,(res)=>{
        if(res.data.success==1){
          loginMsg.bindingPhone = true
          wx.setStorageSync('loginMsg', loginMsg)
          this.setData({
            getPhoneNumberData:{
              isShowGetPhoneNumber:false
            }
          })
          wx.showToast({
            title: '绑定成功。',
          })
          this.getcenterCount()
        }
      })
    } else {
      console.log('取消')
      this.getcenterCount()
    }
  },
  /**  绑定手机号 ---end*/
})
